package com.hroay.netty02.bio;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author heyingcheng
 * @category Class description
 * @email heyingcheng@ctvit.com.cn
 * @date 2018/2/1 16:36
 */
@Slf4j
public abstract class TimeServer {

    protected int port;

    protected ServerSocket serverSocket;

    public TimeServer(int port) {
        this.port = port;
    }

    public abstract void initTask();

    public abstract void startTask(Socket socket);

    public void startServer() {
        try {
            serverSocket = new ServerSocket(port);
        } catch (IOException e) {
            e.printStackTrace();
        }
        initTask();
        try {
            while(true) {
                Socket socket = serverSocket.accept();
                startTask(socket);
                new Thread(new TimeServerHandler(socket)).start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (serverSocket != null) {
                log.info("The time server close");
                try {
                    serverSocket.close();
                    serverSocket = null;
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
